<!--
 * @Descripttion: 转库单
 * @Autor: zhouchen
 * @Date: 2020-11-08 15:26:52
 * @LastEditTime: 2021-11-13 20:00:27
-->


<template>
  <a-card>
    <!-------------- 上方表单 -------------->
    <a-form-model
      :model="queryform"
      v-bind="layout"
      :rules="rules"
      ref="ruleForm"
    >
      <div style="margin-bottom: 3%">
        <a-row>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24" align="center">
            <span style="font-size: 150%">转库单</span>
          </a-col>
        </a-row>
      </div>
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号" ref="document" prop="document">
            <a-input disabled v-model="queryform.document" />
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="单据日期"
            ref="document_date"
            prop="document_date"
          >
            <a-date-picker
              @change="changeAllDate"
              style="width: 100%"
              v-model="queryform.document_date"
            />
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="出库仓库"
            ref="outboundHouse"
            prop="outboundHouse"
          >
            <a-select
              showSearch
              placeholder="请选择仓库"
              v-model="queryform.outboundHouse"
              @change="changeOutWarhouse"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="item.depotId + '|' + item.depotName"
                >{{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="入库仓库"
            ref="inboundHouse"
            prop="inboundHouse"
          >
            <a-select
              showSearch
              placeholder="请选择仓库"
              v-model="queryform.inboundHouse"
              @change="changeInWarhouse"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="item.depotId + '|' + item.depotName"
                >{{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="收发类别" ref="sarType" prop="sarType">
            <a-select
              showSearch
              placeholder="请选择收发类别"
              v-model="queryform.sarType"
            >
              <a-select-option
                v-for="item in sarTypeList"
                :key="item.value"
                :value="item.value + '|' + item.title"
                >{{ item.title }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司" ref="corp" prop="corp">
            <a-tree-select
              v-model="queryform.corp"
              show-search
              style="width: 100%"
              allow-clear
              :tree-data="CorpList"
              @change="getCorpId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织" ref="bodyname" prop="bodyname">
            <a-select
              v-model="queryform.bodyname"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.id"
                :value="item.pkCalbody + '|' + item.bodyname"
              >
                {{ item.bodycode }}
                {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="备注">
            <a-input
              style="width: 100%"
              placeholder
              v-model="queryform.remarks"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-------------- 单据表格 -------------->
      <a-table
        :columns="columns"
        :data-source="data"
        :scroll="{ x: 2000 }"
        :pagination="false"
        :rules="rules"
        :rowKey="
          (record, index) => {
            return index;
          }
        "
      >
        <!-- 存货编码可编辑插槽  -->
        <span slot="inventoryName" slot-scope="text, record">
          <a-select
            v-model="record.inventoryName"
            style="width: 100%"
            @search="handleSearch"
            @focus="getKeyForInventorySearch(record.key)"
            @change="getInventoryInfo(record.key)"
            showSearch
          >
            <a-select-option
              v-for="item in record.goodsList"
              :key="item.inventory_id"
              :value="
                item.inventory_id +
                '|' +
                item.inventory_no +
                '|' +
                item.inventory_name +
                '|' +
                item.specificationsModel +
                '|' +
                item.unit
              "
              >{{ item.inventory_no }} {{ item.inventory_name }}
              {{ item.specificationsModel }}
            </a-select-option>
          </a-select>
        </span>
        <!-- 数量 -->
        <span slot="quantity" slot-scope="text, record">
          <a-input-number
            v-model="record.quantity"
            :min="0"
            style="width: 100%"
            :precision="3"
          />
        </span>

        <!-- 金额 -->
        <span slot="amount" slot-scope="text, record">
          <a-input-number
            v-model="record.amount"
            :min="0"
            style="width: 100%"
            :precision="2"
          />
        </span>
        <!-- 出库仓库可编辑插槽 -->
        <span slot="dischargeHouse" slot-scope="text, record">
          <a-select
            showSearch
            v-model="record.dischargeHouse"
            @change="getOutLocationInData(record)"
          >
            <a-select-option
              v-for="item in storageList"
              :key="item.depotId"
              :value="item.depotId + '|' + item.depotName"
              >{{ item.depotName }}</a-select-option
            >
          </a-select>
        </span>
        <!-- 出库库位可编辑插槽 -->
        <!-- <span slot="outboundLocation" slot-scope="text, record">
          <a-tree-select
            v-model="record.outboundLocation"
            style="width: 100%"
            :tree-data="record.outPositionList"
            allow-clear
          ></a-tree-select>
        </span> -->
        <!-- 出库仓位可编辑插槽 -->
        <span slot="dischargeBin" slot-scope="text, record">
          <a-tree-select
            v-model="record.dischargeBin"
            style="width: 100%"
            :tree-data="record.outPositionList"
            allow-clear
          ></a-tree-select>
        </span>
        <!-- 入库仓库可编辑插槽 -->
        <span slot="receivingHouse" slot-scope="text, record">
          <a-select
            showSearch
            v-model="record.receivingHouse"
            @change="getInLocationInData(record)"
          >
            <a-select-option
              v-for="item in storageList"
              :key="item.depotId"
              :value="item.depotId + '|' + item.depotName"
              >{{ item.depotName }}</a-select-option
            >
          </a-select>
        </span>
        <!-- 入库库位可编辑插槽 -->
        <!-- <span slot="inboundLocation" slot-scope="text, record">
          <a-tree-select
            v-model="record.inboundLocation"
            style="width: 100%"
            :tree-data="record.inPositionList"
            allow-clear
          ></a-tree-select>
        </span> -->
        <!-- 入库仓位可编辑插槽 -->
        <span slot="receivingBin" slot-scope="text, record">
          <a-tree-select
            v-model="record.receivingBin"
            style="width: 100%"
            :tree-data="record.inPositionList"
            allow-clear
          ></a-tree-select>
        </span>
        <!-- 批次号可编辑插槽 -->
        <span slot="batchNo" slot-scope="text, record">
          <a-select v-model="record.batchNo" style="width: 100%" showSearch>
            <a-select-option
              v-for="(item, index) in record.batchList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </span>
        <!-- 转库日期可编辑插槽 -->
        <span slot="transferDate" slot-scope="text, record">
          <a-date-picker v-model="record.transferDate" />
        </span>
        <!-- 备注可编辑插槽 -->
        <span slot="remarks" slot-scope="text, record">
          <a-input v-model="record.remarks" />
        </span>
        <span slot="options" slot-scope="text, record">
          <a href="#" @click="cancle(record.key)">取消</a>
        </span>
      </a-table>
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        >添加</a-button
      >
      <!-------------- 表格下方输入框 -------------->
      <div style="margin-top: 2%">
        <a-row>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24" align="left">
            <a-form-model-item label="审核人" ref="reviewer" prop="reviewer">
              <a-select showSearch placeholder v-model="queryform.reviewer">
                <a-select-option
                  v-for="item in chargeList"
                  :key="item.userId"
                  :value="item.userId + '|' + item.userName"
                  >{{ item.userName }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期" ref="balance" prop="balance">
              <a-date-picker
                style="width: 100%"
                disabled
                v-model="queryform.balance"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人">
              <a-input v-model="queryform.single_producer" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div style="margin-top: 2%">
          <center>
            <a-button type="primary" @click="save" style="margin-right: 2%"
              >保存</a-button
            >
            <a-button
              :disabled="!ExamineTag"
              @click="Examine"
              style="margin-right: 2%"
              >审核</a-button
            >
            <!-- <a-button type="primary" disabled>提交</a-button> -->
          </center>
        </div>
      </div>
    </a-form-model>
  </a-card>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax();

import { ZhuanKu } from "@/services/modules/KuCunTiaoZheng/ZhuanKu.js";
const zhuankuHttp = new ZhuanKu();

import { ZhuanKuLieBiao } from "@/services/modules/KuCunTiaoZheng/ZhuanKuLieBiao.js";
const zhuankuliebiaoHttp = new ZhuanKuLieBiao();

// 引入
import moment from "moment";
import "moment/locale/zh-cn";

import { mapState } from "vuex";

const columns = [
  {
    title: "序号",
    dataIndex: "lineNo",
    key: "lineNo",
    align: "center",
    width: 200,
  },
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
    scopedSlots: { customRender: "inventoryNo" },
    width: 200,
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
    scopedSlots: { customRender: "inventoryName" },
    width: 500,
  },
  {
    title: "规格型号",
    dataIndex: "specificationsModel",
    key: "specificationsModel",
    align: "center",
    width: 200,
  },
  {
    title: "单位",
    dataIndex: "unit",
    key: "unit",
    align: "center",
    width: 200,
  },
  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
    width: 200,
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "金额",
    dataIndex: "amount",
    key: "amount",
    align: "center",
    width: 200,
    scopedSlots: { customRender: "amount" },
  },
  {
    title: "出库仓库",
    dataIndex: "dischargeHouse",
    key: "dischargeHouse",
    align: "center",
    scopedSlots: { customRender: "dischargeHouse" },
    width: 200,
  },
  // {
  //   title: "出库库位",
  //   dataIndex: "outboundLocation",
  //   key: "outboundLocation",
  //   align: "center",
  //   scopedSlots: { customRender: "outboundLocation" },
  //   width: 200,
  // },
  {
    title: "出库仓位",
    dataIndex: "dischargeBin",
    key: "dischargeBin",
    align: "center",
    scopedSlots: { customRender: "dischargeBin" },
    width: 200,
  },
  {
    title: "入库仓库",
    dataIndex: "receivingHouse",
    key: "receivingHouse",
    align: "center",
    scopedSlots: { customRender: "receivingHouse" },
    width: 200,
  },
  // {
  //   title: "入库库位",
  //   dataIndex: "inboundLocation",
  //   key: "inboundLocation",
  //   align: "center",
  //   scopedSlots: { customRender: "inboundLocation" },
  //   width: 200,
  // },
  {
    title: "入库仓位",
    dataIndex: "receivingBin",
    key: "receivingBin",
    align: "center",
    scopedSlots: { customRender: "receivingBin" },
    width: 200,
  },
  {
    title: "批次号",
    dataIndex: "batchNo",
    key: "batchNo",
    align: "center",
    scopedSlots: { customRender: "batchNo" },
    width: 200,
  },
  {
    title: "转库日期",
    dataIndex: "transferDate",
    key: "transferDate",
    align: "center",
    scopedSlots: { customRender: "transferDate" },
    width: 200,
  },
  {
    title: "备注",
    dataIndex: "remarks",
    key: "remarks",
    align: "center",
    scopedSlots: { customRender: "remarks" },
    width: 300,
  },
  {
    title: "操作",
    dataIndex: "options",
    key: "options",
    align: "center",
    scopedSlots: { customRender: "options" },
    width: 100,
  },
];

const data = [];

export default {
  computed: {
    // 获取本地数据
    ...mapState("user", { currUser: "info", currPost: "position" }),
  },

  data() {
    return {
      keykey: 0,
      // ----------- 通用变量 -----------
      // 获取当前列的key值
      currentKey: "",

      // 审核相关
      checkTag: false, // 审核标志
      updateTag: false, // 修改标志
      alreadyCheckTag: false, // 没审核
      ExamineTag: "", // 审核标志

      // ----------- 查询表单 -----------
      // 仓库下拉框
      storageList: [],

      // 下拉框 收发类别
      sarTypeList: [],

      // 查询表单数据
      queryform: {
        inWarehouseId: "", // 获取入库仓库Id
        outWarehouseId: "", // 获取出库仓库Id
        document: "",
        document_date: "",
        outboundHouse: "",
        inboundHouse: "",
        sarType: "",
        remarks: "",
        reviewer: "",

        single_producer: this.$store.state.user.info.username,
        single_producer_id: this.$store.state.user.info.id,
        balance: "", // 审核日期

        corp: "", //公司名称
        corpId: "1000", //公司id
        bodyname: "", //这个是库存组织名称
        pkCalbody: "1001F3100000000002LS", //这个是库存组织id
      },

      // 表单的格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },
      empty_: true,

      // ----------- 单据表格 -----------
      // 表头
      columns,

      // 数据源
      data,
      CorpList: [], //公司列表
      InventoryOrganizationList: [], // 库存组织列表

      // 中间变量 仓位
      positionList: [],

      // ----------- 表格下方下拉框 -----------
      // 负责人下拉框
      chargeList: [],
      //规则
      rules: {
        document: [
          {
            required: true,
            message: "单据号不能为空！",
            trigger: "change",
          },
        ],
        document_date: [
          {
            required: true,
            message: "单据日期不能为空！",
            trigger: "change",
          },
        ],
        outboundHouse: [
          {
            required: true,
            message: "出库仓库不能为空！",
            trigger: "change",
          },
        ],
        inboundHouse: [
          {
            required: true,
            message: "入库仓库不能为空！",
            trigger: "change",
          },
        ],
        bodyname: [
          {
            required: true,
            message: "库存组织不能为空！",
            trigger: "blur",
          },
        ],
        inventoryName: [
          {
            required: true,
            message: "存货名称不能为空！",
            trigger: "change",
          },
        ],
        inventoryNo: [
          {
            required: true,
            message: "存货编码不能为空！",
            trigger: "change",
          },
        ],
        sarType: [
          {
            required: true,
            message: "收发类别不能为空！",
            trigger: "blur",
          },
        ],
        corp: [
          {
            required: true,
            message: "公司不能为空！",
            trigger: "change",
          },
        ],
        reviewer: [
          {
            required: true,
            message: "审核人不能为空！",
            trigger: "change",
          },
        ],
      },
    };
  },

  watch: {
    $route: function (to, form) {
      if (to.path == "/Redeposit" && form.path == "/RedepositList") {
        console.log("--------- 更新视图 组装  ----------");

        if (this.$route.query.Id) {
          this.getRouterParam();
        }
      } else {
        this.ResetForm();
      }
    },
  },

  mounted() {
    this.judgeDocument(); //判断单据号是否为空

    // 初始化表格
    this.setDataSource();
    // 获取仓库
    this.getApplyStorage();
    // 初始化表格内日期 为当日日期
    this.initializationDate();
    // 获取审核人
    this.getInspectorList();
    // 获取收发类别
    this.getSendReceiveList();
    // 获取单据号
    this.getApplyOrder();
    // 获取路由参数
    this.getRouterParam();
    //获取公司
    this.getCorpInfo();
    //获取库存组织
    this.getSyncInventoryOrganizationList(); //获取库存组织列表
  },
  methods: {
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.queryform.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    // ----------- 通用 -----------
    // 获取单号
    getApplyOrder() {
      let queryPath = "?string=ZKDD-";
      comHttp.getOrder(queryPath).then((res) => {
        this.queryform.document = res.message;
      });
    },

    // 获取路由参数
    getRouterParam() {
      console.log("查询参数:::", this.$route.query.Id);
      console.log("----- 标志位 -----", this.$route.query.ExamineTag);
      // 通过出入库id 查询出入库信息
      if (typeof this.$route.query.Id == "undefined") {
        this.ExamineTag = this.$route.query.ExamineTag;
        console.log("常规跳转");
      } else {
        this.setInitInfo(this.$route.query.Id);
      }
    },

    // 根据路由传递id初始化表单信息
    setInitInfo(id) {
      this.data = [];
      zhuankuliebiaoHttp
        .getWarehouseTransferList(`?id=${id}&pageSize=200&pageNo=1`)
        .then(async (res) => {
          console.log("----- routerListRes -----", res);
          let getData = res.result.records[0];
          this.queryform.id = getData.id;
          this.queryform.document = getData.document;
          this.queryform.document_date = getData.documentDate;
          this.queryform.outboundHouse =
            getData.outboundWarehouseId +
            "|" +
            getData.outboundWarehouseId_dictText;
          this.queryform.inboundHouse =
            getData.inWarehouseId + "|" + getData.inWarehouseId_dictText;
          this.queryform.sarType =
            getData.category + "|" + getData.category_dictText;
          this.queryform.remarks = getData.remark;
          this.queryform.reviewer =
            getData.reviewer + "|" + getData.reviewer_dictText;
          this.queryform.single_producer = getData.reparedBy_dictText;
          this.queryform.single_producer_id = getData.reparedBy;
          // 将数据赋值给表格
          let array = res.result.records;
          let resArray = [];
          for (let i = 0; i < array.length; i++) {
            let singleData = {
              batchList: await this.getBatchNumberList(
                array[i].inventoryId,
                array[i].outboundWarehouseId
              ),
              key: i + 1,
              lineNo: i + 1,
              id: array[i].twoId, // id
              inventoryId: array[i].inventoryId, // 存货id
              inventoryNo:
                array[i].inventoryNo + "|" + array[i].inventoryId_dictText, // 存货编码
              inventoryName: array[i].inventoryId_dictText, // 存货名称
              specificationsModel: array[i].specificationsModel, // 规格型号
              unit: array[i].unit, //单位
              quantity: array[i].number, // 数量
              amount: array[i].money, // 金额
              outPositionList: [],
              inPositionList: [],
              dischargeHouse:
                array[i].outboundWarehouseId +
                "|" +
                array[i].outboundWarehouseId_dictText, // 出库仓库
              // outboundLocation: array[i].outboundLocation, // 出库库位
              dischargeBin: array[i].outboundPosition, // 出库仓位
              receivingHouse:
                array[i].inWarehouseId + "|" + array[i].inWarehouseId_dictText, // 入库仓库
              //inboundLocation: array[i].inboundLocation, // 入库库位
              receivingBin: array[i].inboundPosition, // 入库仓位
              batchNo: array[i].batchNo, // 批次号
              transferDate: array[i].documentDate, // 转库日期
              remarks: array[i].remark, // 备注
              // goodsList: await this.getInventoryCode(
              //   array[i].outboundWarehouseId
              // ),
            };
            console.log(111);

            const fsOutList = await this.getPositionList(
              getData.outboundWarehouseId
            );
            const fsInList = await this.getPositionList(getData.inWarehouseId);
            console.log(22);
            console.log("fsOutList", fsOutList);
            const scOutList = await this.disableParent(fsOutList);
            this.$set(singleData, "outPositionList", scOutList);

            const scInList = await this.disableParent(fsInList);
            this.$set(singleData, "inPositionList", scInList);
            console.log("----- singleData -----", singleData);
            resArray.push(singleData);
          }
          this.data = resArray;
          console.log("this.data", this.data);
        });
      this.updateTag = true;
      if (this.$route.query.ExamineTag)
        this.ExamineTag = this.$route.query.ExamineTag;
    },

    // 获取批次号
    getBatchNumberList(invId, depotId) {
      let temp = [];
      return new Promise((resolve) => {
        comHttp
          .getgetBatchNumberById(
            "?depotId=" + depotId + "&inventoryId=" + invId
          )
          .then((res) => {
            console.log("获取批次号res", res);
            temp = res.result;
            resolve(temp);
          });
      });
    },

    // 转换undefined
    turnUndefined(option) {
      if (option === undefined) option = "";
      return option;
    },

    // 获取仓库
    getApplyStorage() {
      //默认库存组织为七河生物
      this.$set(
        this.queryform,
        "bodyname",
        "1001F3100000000002LS|山东七河生物"
      );
      //默认公司为七河生物
      this.$set(this.queryform, "corp", "1000 山东七河生物科技股份有限公司");
      this.storageList = [];
      // 获取仓库名称
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    // 禁用父节点
    disableParent(Tree) {
      return new Promise((resolve) => {
        Tree.forEach((item) => {
          // console.log(item);
          if (item.children.length != 0) {
            item[`disabled`] = true;
          } else {
            this.disableParent(item.children);
          }
        });
        resolve(Tree);
      });
    },

    /*   
    当移入鼠标焦点时，获得当前列的key值，进行储存
    便于对某一行中的goodsList进行操作 
    */
    getKeyForInventorySearch(key) {
      this.currentKey = key;
    },

    // 模糊查询 存货编码
    async handleSearch(value) {
      var goodsList_invname = [];
      var goodsList_invspec = [];

      console.log("value", value);
      let query = "?name=" + value;
      // 使用正则表达式 判断输入的字符中是否有空格
      let reg = /^\s*(\S+)\s*$/;
      // 若有 则去空格
      if (reg.test(value)) value = RegExp.$1;
      // 若没有 全是空格 则置空
      else value = "";
      // console.log("query", query);
      if (value == "" || value == null) {
        this.goodsList = [];
      } else {
        await comHttp
          .getgetSearchInventoryInformationFile(query)
          .then((res) => {
            console.log("结果为", res);
            // this.goodsList = res.result;
            for (let i = 0; i < res.result.length; i++) {
              if (
                res.result[i].specificationsModel == "null" ||
                res.result[i].specificationsModel == null
              ) {
                res.result[i].specificationsModel = "";
              }
              if (res.result[i].unit == "null" || res.result[i].unit == null) {
                res.result[i].unit = "";
              }
              let data = {
                inventory_id: res.result[i].pkInvbasdoc,
                inventory_no: res.result[i].invcode,
                inventory_name: res.result[i].invname,
                specificationsModel: res.result[i].invspec,
                unit: res.result[i].measname,
              };
              goodsList_invname.push(data);

              //measname  dawnei minghceng
              //invspec 规格 invtype 型号
            }
          });

        let queryInventoryBySpec = "?invspec=" + value;
        //规格型号模糊查询
        await comHttp
          .getqueryInventoryBySpec(queryInventoryBySpec)
          .then((res) => {
            console.log("结果规格型号模糊查询", res);

            for (let i = 0; i < res.result.list.length; i++) {
              let data = {
                inventory_id: res.result.list[i].pkInvbasdoc, // 存货 id
                inventory_no: res.result.list[i].invcode, //存货编码
                inventory_name: res.result.list[i].invname, //存货名称
                specificationsModel: res.result.list[i].invspec, //规格型号
                unit: res.result.list[i].measname, //单位
              };
              goodsList_invspec.push(data);
            }
          });
        //todo 合并去重函数
        await this.mergeArray(goodsList_invname, goodsList_invspec);
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];

      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventory_id)) {
          map.set(item.inventory_id, item);
        }
      }
      this.goodsList = [...map.values()]; //将

      this.$set(this.data[this.currentKey - 1], "goodsList", this.goodsList);
    },
    // // 获取存货编码和存货信息
    // getInventoryCode(id) {
    //   let _list = [];
    //   return new Promise((resolve) => {
    //     comHttp.getInventoryInformationByStorageId("?id=" + id).then((res) => {
    //       let array = res.result;
    //       console.log("----- arrayIn -----", array);
    //       for (let i = 0; i < array.length; i++) {
    //         let singleData = {
    //           inventory_id: array[i].id,
    //           inventory_no: array[i].inventoryNo,
    //           inventory_name: array[i].inventoryName,
    //           specificationsModel: array[i].specificationsModel,
    //           unit: array[i].unit,
    //         };
    //         _list.push(singleData);
    //       }
    //     });
    //     resolve(_list);
    //   });
    // },

    // 获取仓位列表
    getPositionList(id) {
      let positionList = [];
      return new Promise((resolve) => {
        comHttp.getPositionInformationListByDepotId("?id=" + id).then((res) => {
          console.log("----- res -----", res);
          if (res.result.length !== 0) {
            positionList = res.result[0].children;
            console.log("----- positionList -----", positionList);
            resolve(positionList);
          } else {
            resolve(positionList);
          }
        });
      });
    },
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },

    // 获取审核人及制单人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.chargeList.push(data);
        }
      });
    },

    // 获取收发类别列表
    getSendReceiveList() {
      this.sarTypeList = [];
      comHttp.getReceiveSendTypeListAll().then((res) => {
        console.log("收发类别列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].id,
            title: res.result[i].name,
          };
          this.sarTypeList.push(data);
        }
      });
    },

    // ----------- 页面底按钮触发函数 -----------
    // 审核函数
    Examine() {
      this.queryform.balance = moment().format("YYYY-MM-DD");
      console.log(this.queryform.balance);
      let dataArray = [];
      this.data.forEach((data) => {
        let singleData = {
          // 审核人审核 并进行入库仓位/库位的填写
          id: data.id,
          //inboundLocation: this.turnUndefined(data.inboundLocation),
          inboundPosition: this.turnUndefined(data.receivingBin),
        };
        dataArray.push(singleData);
      });
      console.log("----- dataArray -----", dataArray);
      let data = {
        id: this.queryform.id,
        auditMark: 1,
        balance: this.queryform.balance,
        warehouseTransferLibraryFormEntity: dataArray,
      };
      // 提交审核信息，修改表一数据
      zhuankuHttp.postUpdateWarhouseTransfer(data).then((res) => {
        if (res.code == 200) {
          this.$message.success("审核成功");
          this.alreadyCheckTag = false;
        } else {
          this.$message.error("审核失败");
        }
      });
    },

    // 保存
    save(e) {
      console.log("----- saveE -----", e);
      if (!this.updateTag) {
        this.addWarhouseTransfer();
        // this.retundata();
      } else {
        console.log("----- 更新表单 -----");
        this.updateWarhouseTransfer();
      }
    },

    // 新增数据
    addWarhouseTransfer() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.checkempty(); //校验
          let dataArray = [];
          this.data.forEach((data) => {
            console.log("----- data -----", data);
            if (data.inventoryId !== undefined) {
              let singleData = {
                batchNo: data.batchNo,
                //inboundLocation: this.turnUndefined(data.inboundLocation),
                inboundPosition: this.turnUndefined(data.receivingBin),
                inventoryId: data.inventoryId,
                money: this.turnUndefined(data.amount),
                number: this.turnUndefined(data.quantity),
                //outboundLocation: this.turnUndefined(data.outboundLocation),
                outboundPosition: this.turnUndefined(data.dischargeBin),
                remark: this.turnUndefined(data.remarks),
                transferDate: moment(data.transferDate).format("YYYY-MM-DD"),
              };
              console.log("----- singleData.bathNo -----", singleData.bathNo);
              dataArray.push(singleData);
            }
          });
          console.log("----- dataArray -----", dataArray);
          let saveData = {
            balance: moment(this.queryform.document_date).format("YYYY-MM-DD"),
            auditMark: 2,
            bookkeepingMark: 2,
            category: this.queryform.sarType.split("|")[0],
            document: this.queryform.document,
            documentDate: moment(this.queryform.document_date).format(
              "YYYY-MM-DD"
            ),
            inWarehouseId: this.queryform.inboundHouse.split("|")[0],
            outboundWarehouseId: this.queryform.outboundHouse.split("|")[0],
            remark: this.queryform.remarks,
            reparedBy: this.queryform.single_producer_id,
            reviewDate: "",
            reviewer: this.queryform.reviewer.split("|")[0],
            warehouseTransferLibraryFormEntity: dataArray,

            pkCorp: this.queryform.corpId, // 这是公司id
            pkCalbody: this.queryform.pkCalbody, //这个是库存组织id
          };
          console.log("----- saveData -----", saveData);

          if (this.empty_) {
            zhuankuHttp.postWarhouseTransfer(saveData).then((res) => {
              console.log("----- saveRes -----", res);
              if (res.success) {
                this.$message.success("保存成功");
                this.ResetForm(); //重置
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          console.log("请把头部信息填写完整");
          this.$message.error("请把头部信息填写完整");
        }
      });
    },
    //校验是否为空
    checkempty() {
      this.empty_ = true;
      var message = []; //提示信息
      this.data.forEach((Res) => {
        console.log(Res, "res");
        if (!Res.inventoryNo) {
          message.push("存货编码不能为空!");
          this.empty_ = false;
        }
        if (!Res.transferDate) {
          message.push("转库日期不能为空!");
          this.empty_ = false;
        }
      });

      if (!this.empty_) {
        this.$message.error(message);
      }
    },

    //保存重置表单
    ResetForm() {
      this.queryform = {
        document: "",
        document_date: moment(this.queryform.document_date).format(
          "YYYY-MM-DD"
        ),
        bodyname: "1001F3100000000002LS|山东七河生物",
        corp: "1000 山东七河生物科技股份有限公司",
        outboundHouse: "",
        inboundHouse: "",
        sarType: "",
        remarks: "",
        reviewer: "",
        single_producer: this.$store.state.user.info.username,
        single_producer_id: this.$store.state.user.info.id,
        balance: moment(this.queryform.document_date).format("YYYY-MM-DD"),
      };

      this.data = [];
      this.getApplyOrder();
      this.initializationDate();
      this.setDataSource();
    },
    getCorpInfo() {
      comHttp.getpk_corpList().then((res) => {
        console.log("所有公司信息::::", res);
        this.CorpList = res.result;
        this.changeCorpData(this.CorpList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] =
          element.unitcode + "|" + element.unitname + "|" + element.pkCorp;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;
        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },
    getpk_calbodyId(value) {
      console.log("value", value);
      let array = value.split("|");
      this.queryform.pkCalbody = array[0];
      console.log("this.Form.pkCalbody", this.Form.pkCalbody);
    },

    // 更新数据
    updateWarhouseTransfer() {
      let dataArray = [];
      this.data.forEach((data) => {
        console.log("----- data -----", data);
        let singleData = {
          id: data.id,
          batchNo: data.batchNo,
          //inboundLocation: this.turnUndefined(data.inboundLocation),
          inboundPosition: this.turnUndefined(data.receivingBin),
          inventoryId: data.inventoryId,
          money: this.turnUndefined(data.amount),
          number: this.turnUndefined(data.quantity),
          //outboundLocation: this.turnUndefined(data.outboundLocation),
          outboundPosition: this.turnUndefined(data.dischargeBin),
          remark: this.turnUndefined(data.remarks),
          transferDate: moment(data.transferDate).format("YYYY-MM-DD"),
        };
        console.log("----- singleData.bathNo -----", singleData.bathNo);
        dataArray.push(singleData);
      });
      console.log("----- dataArray -----", dataArray);
      let updateData = {
        id: this.queryform.id,
        auditMark: 2,
        bookkeepingMark: 2,
        category: this.queryform.sarType.split("|")[0],
        document: this.queryform.document,
        documentDate: moment(this.queryform.document_date).format("YYYY-MM-DD"),
        inWarehouseId: this.queryform.inboundHouse.split("|")[0],
        outboundWarehouseId: this.queryform.outboundHouse.split("|")[0],
        remark: this.queryform.remarks,
        reparedBy: this.queryform.single_producer_id,
        reviewDate: "",
        reviewer: this.queryform.reviewer.split("|")[0],
        warehouseTransferLibraryFormEntity: dataArray,

        pkCorp: this.queryform.corpId, // 这是公司id
        pkCalbody: this.queryform.pkCalbody, //这个是库存组织id
      };
      console.log("----- updateData -----", updateData);
      zhuankuHttp.postUpdateWarhouseTransfer(updateData).then((res) => {
        if (res.success) this.$message.success("更新成功");
        else this.$message.error("更新失败");
      });
    },

    // ----------- 上方输入框 -----------
    // 初始化日期
    initializationDate() {
      this.queryform.document_date = moment().format("YYYY-MM-DD");
      this.data = this.data.map((singleData) => ({
        key: singleData.key,
        lineNo: singleData.lineNo,
        transferDate: moment().format("YYYY-MM-DD"),
        outPositionList: [],
        inPositionList: [],
      }));
      this.queryform.balance = moment().format("YYYY-MM-DD");
    },

    // 修改日期后 改变表格中所有日期
    changeAllDate(dateString) {
      console.log(
        "----- queryform.documentDate -----",
        this.queryform.document_date
      );
      this.queryform.balance = dateString;
      this.data.forEach((item, index) => {
        this.data[index].transferDate = dateString;
      });
    },
    // changeAllDate(date, dateString) {
    //   console.log("date", date);
    //   console.log("dateString", dateString);
    //   this.queryform.document_date = dateString;
    //   this.queryform.balance = dateString;
    //   this.data = this.data.map((singleData) => ({
    //     key: singleData.key,
    //     lineNo: singleData.lineNo,
    //     transferDate: moment(this.queryform.document_date).format("YYYY-MM-DD"),
    //   }));
    // },
    // async
    // 点击出库仓库 改变表格内出库仓库 同时获取物品列表
    async changeOutWarhouse(value, options) {
      this.keykey = Math.random();
      console.log(this.keykey);
      let warhouseId = this.queryform.outboundHouse.split("|")[0];

      for (let i = 0; i < this.data.length; i++) {
        this.$set(this.data[i], "dischargeHouse", this.queryform.outboundHouse);
        const fslist = await this.getPositionList(warhouseId);
        console.log("----- fslist -----", fslist);
        const sclist = await this.disableParent(fslist);
        this.data[i].outPositionList = [];
        this.$set(this.data[i], "outPositionList", sclist);
        console.log(
          "----- this.data[i].outPositionList -----",
          i,
          this.data[i].outPositionList
        );
        // const _data = await this.getInventoryCode(warhouseId);
        // this.$set(this.data[i], "goodsList", _data);
      }

      this.queryform.outWarehouseId = options.key;

      console.log("----- Outdata -----", this.data);
    },

    // 点击入库仓库 改变表格内入库仓库
    async changeInWarhouse(value, options) {
      let warhouseId = this.queryform.inboundHouse.split("|")[0];
      for (let i = 0; i < this.data.length; i++) {
        this.$set(this.data[i], "receivingHouse", this.queryform.inboundHouse);
        const fslist = await this.getPositionList(warhouseId);
        const sclist = await this.disableParent(fslist);
        this.data[i].inPositionList = [];
        this.$set(this.data[i], "inPositionList", sclist);
        // const _data = await this.getInventoryCode(warhouseId);
        // this.$set(this.data[i], "goodsList", _data);
      }
      this.queryform.inWarehouseId = options.key;

      console.log("----- Indata -----", this.data);
    },

    // ----------- 表格相关函数 -----------
    // 可编辑表格 获取存货信息
    async getInventoryInfo(key) {
      console.log("这是可编辑的表格", key);
      let target = this.data.filter((item) => item.key === key)[0];
      // 分割字符串,取出来存货编码
      let array = target.inventoryName.split("|");
      console.log("array", array);
      this.$set(target, "inventoryNo", array[1]); // 赋值给存货编码
      this.$set(target, "inventoryName", array[2]); // 赋值给存货名称

      let goodsInfomation = target.goodsList.filter(
        (item) => item.inventory_no === array[1]
      )[0];
      this.$set(target, "inventoryId", goodsInfomation.inventory_id); //赋值存货Id
      this.$set(
        target,
        "specificationsModel",
        goodsInfomation.specificationsModel
      ); // 赋值规格型号
      this.$set(target, "unit", goodsInfomation.unit); // 赋值单位
      console.log(target);

      if (target.dischargeHouse) {
        const _list = await this.getBatchNumberList(
          target.inventoryId,
          target.dischargeHouse.split("|")[0]
        );
        this.$set(target, "batchList", _list);
      }

      // const _data = await this.getInventoryCode();
      // this.$set(target, "goodsList", _data);

      // let getNumberData = {
      //   depotId: this.queryform.inWarehouseId,
      //   inventoryId: goodsInfomation.inventory_id,
      // };

      // this.$set(
      //   target,
      //   "existingQuantity",
      //   await this.getTotalGoods(getNumberData)
      // ); // 存货编码
    },

    // 选择表格内出库仓库 获取出库仓位和出库库位列表 以及存货列表
    async getOutLocationInData(record) {
      let target = this.data.filter((item) => item.key === record.key)[0];
      console.log("----- outRecord -----", record);
      let warhouseId = record.dischargeHouse.split("|")[0];
      const fslist = await this.getPositionList(warhouseId);
      const sclist = await this.disableParent(fslist);
      this.$set(target, "outPositionList", sclist);
      // const _data = await this.getInventoryCode(warhouseId);
      // this.$set(target, "goodsList", _data);
      console.log("----- finish -----", target);
    },

    // 选择表格内出库仓库 获取出库仓位和出库库位列表
    async getInLocationInData(record) {
      let target = this.data.filter((item) => item.key === record.key)[0];
      console.log("----- inRecord -----", record);
      let warhouseId = record.receivingHouse.split("|")[0];
      const fslist = await this.getPositionList(warhouseId);
      const sclist = await this.disableParent(fslist);
      this.$set(target, "inPositionList", sclist);
      console.log("----- finish -----", target);
    },
    getCorpId(value, label, extra) {
      console.log(label);
      console.log(extra);
      let array = value.split("|");
      console.log("array", array);
      this.queryform.corpId = array[2];
    },

    // 初始化表格 默认一行 出入库成对
    setDataSource() {
      let size = 1;
      this.data = [];
      for (let i = 0; i < size; i++) {
        let singleData = {
          key: i + 1,
          lineNo: i + 1,
          inventoryId: "", // 存货id
          inventoryNo: "", // 存货编码
          inventoryName: "", //  存货名称
          specificationsModel: "", // , 规格型号
          unit: "", // 单位
          quantity: "", // 数量
          amount: "", // 金额
          dischargeHouse: "", // 出库仓库
          //outboundLocation: "", // 出库库位
          // dischargeBin: "", // 出库仓位
          receivingHouse: "", // 入库仓库
          //inboundLocation: "", // 入库库位
          receivingBin: "", // 入库仓位
          batchNo: "", // 批次号
          transferDate: moment().format("YYYY-MM-DD"), // 转库日期
          remarks: "", // 备注
          goodsList: [], // 物品信息列
          batchList: [], // 批次号列
          outPositionList: [], // 仓位库位列表
          inPositionList: [], // 仓位库位列表
        };
        this.data.push(singleData);
      }
    },

    // 表格添加新的记录
    newMember() {
      this.data.push({
        key: this.data.length + 1,
        lineNo: this.data.length + 1,
        inventoryId: "", // 存货id
        inventoryNo: "", // 存货编码
        inventoryName: "", //  存货名称
        specificationsModel: "", // , 规格型号
        unit: "", // 单位
        quantity: "", // 数量
        amount: "", // 金额
        dischargeHouse: "", // 出库仓库
        //outboundLocation: "", // 出库库位
        dischargeBin: "", // 出库仓位
        receivingHouse: "", // 入库仓库
        //inboundLocation: "", // 入库库位
        receivingBin: "", // 入库仓位
        batchNo: "", // 批次号
        transferDate: moment(this.queryform.document_date).format("YYYY-MM-DD"), // 转库日期
        remarks: "", // 备注
        goodsList: [], // 物品信息列
        batchList: [], // 批次号列
        outPositionList: [], // 仓位库位列表
        inPositionList: [], // 仓位库位列表
      });
    },

    // 删除表格中的记录
    cancle(key) {
      // console.log(key);
      if (this.data.length > 1) {
        this.data.splice(key - 1, 1);
        // 对序号进行重新赋值
        for (let i = key - 1; i < this.data.length; i++) {
          this.data[i].key = i + 1;
        }
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },
  },
};
</script>

<style>
</style>